import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import store from '@/store'
import { loginApi, logoutApi } from '@/api/auth'
import { hotModuleUnregisterModule } from '@/utils/helper/vuexHelper'
import { getToken, setToken } from '@/utils/helper/cookieHelper'
import { LoginParams } from '@/types/request'

const MODULE_NAME = 'user'
hotModuleUnregisterModule(MODULE_NAME)

@Module({ name: MODULE_NAME, dynamic: true, namespaced: true, store })
export default class UserModule extends VuexModule {
  token: string = getToken() || ''

  @Mutation
  commitToken (info: string) {
    this.token = info
  }

  @Action
  async login (params: LoginParams) {
    const data = await loginApi(params)
    if (data.code === 0) {
      this.commitToken(data.data.token)
      setToken(data.data.token)
    } else {
      this.commitToken('')
      setToken('')
    }
  }

  @Action
  async logout () {
    const data = await logoutApi()
    if (data.code === 0) {
      this.commitToken('')
      setToken('')
    }
  }
}

export const userStore = getModule(UserModule)
